#include "StdAfx.h"


LiquidHandler::LiquidHandler(CMpqFile* file, ui32 ofsMH2O, Vertex2F chunkBase) : m_file(file)
{
	file->SetInc(0x14 + ofsMH2O + 4);
	ui32 size;
	file->ReadInc(4, &size);
	LiquidHeader headers[256];
	file->ReadInc(256 * sizeof(LiquidHeader), headers);
	ui32 baseOffset = ofsMH2O + 0x14 + 0x8;
	for(ui32 i = 0; i < 16; ++i)
	{
		for(ui32 j = 0; j < 16; ++j)
		{
			if(!headers[i * 16 + j].nLayers)
				continue;

			LiquidInformation* pInformation = new LiquidInformation[headers[i * 16 + j].nLayers];
			file->Read(baseOffset + headers[i * 16 + j].ofsInformation, headers[i * 16 + j].nLayers * sizeof(LiquidInformation), pInformation);
			ui8 mask[8];
			file->Read(baseOffset + headers[i * 16 + j].renderMask, 8, mask);
			for(ui32 k = 0; k < headers[i * 16 + j].nLayers; ++k)
				LoadLayer(pInformation[k], ofsMH2O, (ui8*)mask, Vertex2F(chunkBase.x + j * CHUNKSIZE, chunkBase.y + i * CHUNKSIZE));
			delete [] pInformation;
		}
	}
}

void LiquidHandler::LoadLayer(LiquidInformation& info, ui32& baseOffset, ui8* mask, Vertex2F& cb)
{
	if(info.flags & 1)
		return;

	float baseX = info.xOffset * BLOCKSIZE;
	float baseZ = info.yOffset * BLOCKSIZE;

	float* heights = 0;
	if(!(info.flags & 1))
	{
		heights = new float[info.width * info.height];
		m_file->Read(baseOffset + info.heightmap, info.width * info.height * 4, heights);
	}

	for(ui32 i = 0; i < info.height; ++i)
	{
		for(ui32 j = 0; j < info.width; ++j)
		{
			if(!(mask[i] & (1 << j)))
				continue;
			LiquidQuad q;
			q.m_vertices[0].x = cb.x + baseX + i * BLOCKSIZE;
			q.m_vertices[0].z = cb.y + baseZ + j * BLOCKSIZE;
			float height;
			//if(!(info.flags & 1))
				height = heights[i * info.width + j];
			//else
			//	height = info.heightLevel2;
			q.m_vertices[0].y = q.m_vertices[1].y = q.m_vertices[2].y = q.m_vertices[3].y = height;
			q.m_vertices[1].x = cb.x + baseX + i * BLOCKSIZE;
			q.m_vertices[1].z = cb.y + baseZ + (j + 1) * BLOCKSIZE;
			q.m_vertices[2].x = cb.x + baseX + (i + 1) * BLOCKSIZE;
			q.m_vertices[2].z = cb.y + baseZ + (j + 1) * BLOCKSIZE;
			q.m_vertices[3].x = cb.x + baseX + (i + 1) * BLOCKSIZE;
			q.m_vertices[3].z = cb.y + baseZ + j * BLOCKSIZE;
			q.m_vertices[0].color = q.m_vertices[1].color = q.m_vertices[2].color = q.m_vertices[3].color = 0xFF0000AF;
			m_liquids.push_back(q.m_vertices[0]);
			m_liquids.push_back(q.m_vertices[1]);
			m_liquids.push_back(q.m_vertices[3]);
			m_liquids.push_back(q.m_vertices[3]);
			m_liquids.push_back(q.m_vertices[1]);
			m_liquids.push_back(q.m_vertices[2]);
		}
	}
	if(!(info.flags & 1))
		delete [] heights;
}

void LiquidHandler::Render()
{
	if(m_liquids.size() < 3)
		return;

	sD3D->SetFVF(VERTEX3FC);
	sD3D->DrawPrimitiveUP(D3DPT_TRIANGLELIST, m_liquids.size() / 3, &m_liquids[0], sizeof(Vertex3FC));
}